from app.models.uc.user import User
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession as Session
from app.crud.uc.user import get_user_by_mobile
from app.schemas.uc.user import UserCreate
from app.core.utils import generate_invite_code
from app.crud.uc.user import create_user
from app.schemas.uc.partner_token import PartnerTokenCreate, PartnerTokenUpdate
from app.crud.uc.partner_token import (
    create_partner_token, 
    update_partner_token
)
from app.core.constants import ThirdPartner

async def xm_user_login(session: Session, mobile: str, xm_token: str | None = None) -> User:
    user = await get_user_by_mobile(session=session, mobile=mobile)
    if not user:
        invite_code = generate_invite_code()
        # 新增用户信息
        user_create = UserCreate(
            mobile=mobile,
            inviteCode=invite_code,
        )
        user = await create_user(session=session, user=user_create)
        # 新增XM Token
        partner_token_create = PartnerTokenCreate(
            uid=user.uid,
            partner=1,
            accessToken=xm_token,
        )
        await create_partner_token(session=session, partner_token=partner_token_create)
        return user
    elif user.status != 0:
        raise HTTPException(status_code=400, detail="Inactive user")
    # 更新XM Token
    partner_token_update = PartnerTokenUpdate(
        uid=user.uid,
        partner=ThirdPartner.XMeta,
        accessToken=xm_token,
    )
    await update_partner_token(
        session=session,
        uid=user.uid,
        partner=ThirdPartner.XMeta,
        partner_token=partner_token_update,
    )
    return user